const cache = require("memory-cache");
var request = require("request");
var config = require("./config");
// 设置变量，进行缓存,如果没有缓存尝试调用接口
const accessToken = new cache.Cache();
// 统一处理access_token
const getAccessToken = (callBack) => {
  let access_token = accessToken.get("access_token");
  if (!access_token) {
    // 重新获取access_token
    request(
      "https://api.weixin.qq.com/cgi-bin/token?&grant_type=client_credential&appid=" +
        config.appID +
        "&secret=" +
        config.appSecret,
      function (error, response, body) {
        // Print the response status code if a response was received
        if (!error && response.statusCode == 200) {
          accessToken.put(
            "access_token",
            JSON.parse(body).access_token,
            7000 * 1000,
            () => {
              callBack(body);
            }
          );
        } else {
          callBack(response);
        }
      }
    );
  } else {
    callBack({ access_token });
  }
};

exports.getAccessToken = getAccessToken;
